package com.lkd.job;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.dao.ChannelDao;
import com.lkd.emq.MqttProducer;
import com.lkd.entity.ChannelEntity;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-12-03 14:45
 */
@Component
@Slf4j
public class SupplyAutoJob {

    @Autowired
    private ChannelDao channelDao;
    @Autowired
    private MqttProducer mqttProducer;

    @XxlJob("supplyAuto")
    public void supplyAuto(){

        try{
            int shardIndex = XxlJobHelper.getShardIndex();//服务集群中的序号
            int shardTotal = XxlJobHelper.getShardTotal();//总服务数量
            //1.扫描所有售货机，获取货道缺货信息
            List<ChannelEntity> channelsSupplyData = channelDao.getChannelsSupplyData(shardIndex,shardTotal);

            //售货机集合
            List<String> vms = channelsSupplyData.stream().
                    map(ChannelEntity::getInnerCode).distinct().collect(Collectors.toList());
            System.out.println("序号:" + shardIndex + ",总数量:" + shardTotal);
            System.out.println(vms);
//            for (String innerCode : vms) {
//                //2.包装协议，发送给emq
//                SupplyContract contract = new SupplyContract();
//                contract.setInnerCode(innerCode);
//                List<SupplyChannel> list = channelsSupplyData.stream().
//                        filter(x -> x.getInnerCode().equals(innerCode))
//                        .map(x -> {
//                            SupplyChannel supplyChannel = new SupplyChannel();
//                            //需要的是货道编号 数据库里叫channelCode
//                            supplyChannel.setChannelId(x.getChannelCode());
//                            supplyChannel.setCapacity(x.getMaxCapacity() - x.getCurrentCapacity());
//                            supplyChannel.setSkuId(x.getSkuId());
//                            supplyChannel.setSkuName(x.getSku().getSkuName());
//                            supplyChannel.setSkuImage(x.getSku().getSkuImage());
//                            return supplyChannel;
//                        }).collect(Collectors.toList());
//                contract.setSupplyData(list);
//                try {
//                    mqttProducer.send(TopicConfig.TASK_AUTO_SUPPLY_TOPIC,1,contract);
//                } catch (JsonProcessingException e) {
//                    log.error("发送mq消息json序列化异常",e);
//                }
//            }

        }catch (Exception e){
            log.error("自动创建补货工单消息失败",e);
        }

    }
}
